<template>
    <!-- <a-input-search
        class="search-company"
        placeholder="搜索公司"
        enter-button
        :allowClear="true"
        v-model:value="searchCompany"
    ></a-input-search> -->

    <div class="tree-list">
        <a-tree
            v-if="companyTree"
            :tree-data="companyTree"
            :blockNode="true"
            :autoExpandParent="autoExpandParent"
            @select="(selectedKeys:any[], e:any) =>hdlSelect(selectedKeys,e)"
            :selectedKeys="$attrs.selectedKeys"
            @update:selectedKeys="(keys:any[]) =>changeSelectedKeys(keys) "
            :expandedKeys="$attrs.expandedKeys"
            @update:expandedKeys="(keys:any[]) => $emit('update:expandedKeys', keys)"
            @expand="onExpand"
            :fieldNames="fieldNames"
            :defaultExpandAll="true"
            v-bind="$attrs"
        >
            <template #title="{ title, isDepartment, state, dataId }">
                <div class="tree-item">
                    <div>
                        <span
                            v-if="title && title.indexOf(searchCompany) > -1"
                            class="title"
                            :class="{ disabled: state == 1 }"
                        >
                            {{ title.substr(0, title.indexOf(searchCompany)) }}
                            <span style="color: #6295ff; font-weight: 700">{{
                                searchCompany
                            }}</span>
                            {{
                                title.substr(
                                    title.indexOf(searchCompany) +
                                        searchCompany.length,
                                )
                            }}
                        </span>
                        <span
                            v-else
                            class="title"
                            :class="{ disabled: state == 1 }"
                            >{{ title }}</span
                        >
                    </div>
                    <div class="btns">
                        <img
                            src="@/assets/Lw/modify.png"
                            @click.stop="$emit('modifyDepartment', dataId)"
                            alt=""
                        />
                        <img
                            src="@/assets/Lw/delete.png"
                            @click="$emit('deleteDepartment', dataId)"
                            alt=""
                        />
                    </div>
                </div>
            </template>
        </a-tree>
    </div>
</template>

<script setup lang="ts">
    import { onMounted, ref, useAttrs, watch, inject } from "vue";

    import departmentManageService from "../../service/departmentManage.service";
    import { EllipsisOutlined } from "@ant-design/icons-vue";
    import useGlobalStore from "@/stores/global.store";
    import { storeToRefs } from "pinia";
    import { CompanyTreeInfo } from "@/type/departmentManage";
    const { authApis } = storeToRefs(useGlobalStore());
    // import useGlobalStore from "@/stores/global.store";
    // import { storeToRefs } from "pinia";
    // const globalStore = useGlobalStore();
    // const { userInfo } = storeToRefs(globalStore);

    const fieldNames = {
        children: "children",
        title: "title",
        key: "dataId",
    };

    const props = defineProps<{
        postCompanyListCallBack?: (args?: any) => Promise<any>;
        orgId: any;
        searchCompany: string;
    }>();
    const emit = defineEmits([
        "update:expandedKeys",
        "update:selectedKeys",
        "select",
        "modifyDepartment",
        "deleteDepartment",
    ]);

    const changeIsSelectCompany: any = inject("changeIsSelectCompany");
    const hdlSelect = (selectedKeys: any[], e: any) => {
        let node = e.node;
        if (selectedKeys.length > 0) {
            changeIsSelectCompany(true);
        } else {
            changeIsSelectCompany(false);
        }
        emit("select", selectedKeys, e);
    };
    const changeSelectedKeys = (keys: any[]) => {
        // if (keys.length > 0) {
        //     changeIsSelectCompany(true);
        // } else {
        //     changeIsSelectCompany(false);
        // }
        emit("update:selectedKeys", keys);
    };
    const companyTree = ref<CompanyTreeInfo[]>();

    const show = ref(false);
    const getCompanys = async (isCompanyInfoByUserOrgId = true) => {
        let res = await departmentManageService.getTree(props.orgId);
        let data = res.data.result.data;
        companyTree.value = data;

        // companyTree.value = data[0].children;
        // userOrgId.value = data.userOrgId;
        emit("update:selectedKeys", [data[0].key]);
        if (isCompanyInfoByUserOrgId) {
            props.postCompanyListCallBack && props.postCompanyListCallBack();
        }
        generateList(companyTree.value);
    };
    onMounted(async () => {
        await getCompanys();
    });
    const { searchCompany } = toRefs(props);
    const dataList: any[] = [];
    const generateList = (data: any) => {
        if (data) {
            for (let i = 0; i < data.length; i++) {
                const node = data[i];
                const key = node[fieldNames.key];
                dataList.push({ key, title: node.title });
                if (node.children) {
                    generateList(node.children);
                }
            }
        }
    };

    const getParentKey = (
        key: string | number,
        tree: any,
    ): string | number | undefined => {
        let parentKey;
        for (let i = 0; i < tree.length; i++) {
            const node = tree[i];
            if (node.children) {
                if (
                    node.children.some(
                        (item: any) => item[fieldNames.key] === key,
                    )
                ) {
                    parentKey = node[fieldNames.key];
                } else if (getParentKey(key, node.children)) {
                    parentKey = getParentKey(key, node.children);
                }
            }
        }

        return parentKey;
    };
    const autoExpandParent = ref<boolean>(true);

    watch(searchCompany, (value) => {
        const expanded = dataList
            .map((item: any) => {
                if (item.title.indexOf(value) > -1) {
                    return getParentKey(item.key, companyTree.value);
                }
                return null;
            })
            .filter((item, i, self) => item && self.indexOf(item) === i);

        // expandedKeys.value = expanded;

        emit("update:expandedKeys", expanded);
        // searchCompany.value = value;
        autoExpandParent.value = true;
    });

    const onExpand = (keys: string[]) => {
        // expandedKeys.value = keys;
        emit("update:expandedKeys", keys);
        autoExpandParent.value = false;
    };
    const attrs = useAttrs();
    defineExpose({
        getCompanys,
        companyTree,
        selectedKeys: attrs.selectedKeys,
    });
</script>

<style lang="scss" scoped src="./DepartmentTree.scss"></style>
